package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import jodd.time.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisIdWorker redisIdWorker;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //生成手机校验码;
        //1.判断手机是否为有效的手机号
        //2.有效:生成一份六个数字的验证码
        //3.将生成的验证码存到redis中（string 数据类型）， key = login：code：key ，
//        if (!RegexUtils.isPhoneInvalid(phone)) {
//            return Result.fail("手机号格式错误");
//        }
        //生成检验码，同时把校验码存到redis中
        String code = RandomUtil.randomString(6);
        String key = RedisConstants.LOGIN_CODE_KEY + phone;
        stringRedisTemplate.opsForValue().set(key, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);

        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1. 手机号， 验证码 ，密码
        //1.1 根据手机号格式判断是否正确 ，不符合则返回错误
        //1.2 根据redisopsforvalue.get） key = Login-code-key + phone 获取验证码
        //1.3验证码是否存在， 是否正确， 如果存在且正确 ：
        //1.4 查询数据库有无此用户，没有则创建（单独抽取出创建用户的方法），有则往下
        //1.5 根据uuid随机创建token，后续拦截器也通过token获取手机号，查询是否有此用户
        //1.6：查询用户，user转成userDto ，再转成map 用哈希存储用户信息，
        //UserDTO 转换为 Map<String, Object>
        // 以 token 为 Key，将 userDTO 转换后的 Map 存入 Redis 的 Hash 结构
        //设置有效期
//        if (!RegexUtils.isPhoneInvalid(loginForm.getPhone())) {
//            return Result.fail("手机号错误");
//        }
        String rediscode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + loginForm.getPhone());

        if (rediscode == null || !rediscode.equals(loginForm.getCode())) {
            return Result.fail("验证码错误");
        }
        //用service层的curd进行查找和插入

        User user = query().eq("phone", loginForm.getPhone()).one();

        String phone = loginForm.getPhone();
        if (user == null) {


            user= createUserWithPhone(phone);
        }
        String token = UUID.randomUUID().toString();
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue != null ? fieldValue.toString() : null));
        String key = RedisConstants.LOGIN_USER_KEY +token ;
       stringRedisTemplate.opsForHash().putAll(key, userMap);


       stringRedisTemplate.expire(key, LOGIN_USER_TTL, TimeUnit.MINUTES);
        log.info("登录成功，并延时");

        stringRedisTemplate.delete(LOGIN_CODE_KEY +loginForm.getPhone());

        return Result.ok(token);

    }

    private User createUserWithPhone(String phone) {
        User user1 = new User();
        user1.setPhone(phone);
        user1.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        save(user1);
        return user1;
    }

    @Override
    public Result sign() {
        UserDTO user = UserHolder.getUser();
        LocalDateTime now = LocalDateTime.now();

        String keysuffix =now.format(DateTimeFormatter.ofPattern(":yyyyMMddHHmmss"));
        String key = USER_SIGN_KEY+user.getId()+keysuffix;
        int dayOfMonth = now.getDayOfMonth();
        stringRedisTemplate.opsForValue().setBit(key, dayOfMonth, true);
        return  Result.ok();
    }
    //bitfield key get  u


    @Override
    public Result signCount() {
        Long userId = UserHolder.getUser().getId();
        LocalDateTime now = LocalDateTime.now();

       String keysuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMMddHHmmss"));
        String key = USER_SIGN_KEY + userId + keysuffix;
        int dayOfMonth = now.getDayOfMonth();
        List<Long> result = stringRedisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType
                        .unsigned(dayOfMonth)).valueAt(0)
        );
        if(result == null || result.size() == 0){
            return  Result.ok();
        }
        Long num = result.get(0);
        if(num == null || num == 0){
            return  Result.ok();
        }
        int count =0 ;
        while(true){
            if((num&1)==0){
                break;
            }else if((num&1)==1){
                count++ ;
            }
            num=num>>1;
        }


        return  Result.ok(count);
    }
}
